/**
 * 添加编辑 - 货品
 * @author xiaoxujs
 */

import { Form, Input, message, Modal } from "antd"
import { FC, useEffect } from "react"
import { IPlanInsertGoodsParams, IPlanQueryGoods } from "../../../../../type/productMaintenance";
import { getPlanInsertGoods, postPlanUpdateGoods } from "../../../api";

const AddChangeModule: FC<{
    open: boolean;
    clickData?: IPlanQueryGoods;
    handleCallback: () => void;
}> = ({
    open,
    clickData,
    handleCallback
}) => {
        const [form] = Form.useForm<IPlanInsertGoodsParams>();
        const { validateFields, resetFields, setFieldsValue } = form;

        useEffect(() => {
            if (clickData) {
                setFieldsValue(clickData)
            }
        }, [clickData, setFieldsValue])



        const handleOk = async () => {
            const values = await validateFields();
            if (clickData) {
                const params = {
                    id: clickData.id,
                    ...values
                }
                const { code, msg } = await postPlanUpdateGoods(params) as { code: number, msg: string };
                if (code === 20000) {
                    message.success('修改成功')
                    resetFields()
                    handleCallback();
                } else {
                    message.error(msg)
                }
            } else {
                const { code, msg } = await getPlanInsertGoods(values) as { code: number, msg: string };
                if (code === 20000) {
                    message.success('添加成功')
                    resetFields()
                    handleCallback();
                } else {
                    message.error(msg)
                }
            }

        };

        const handleCancel = () => {
            resetFields()
            handleCallback()
        };
        return <Modal title={clickData ? '修改货品' : '增加货品'} open={open} onOk={handleOk} onCancel={handleCancel}>
            <Form
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
                form={form}
            >
                <Form.Item<IPlanInsertGoodsParams>
                    label="货品名称"
                    name="goodsName"
                    rules={[{ required: true, message: '请输入货物名称!' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    }

export default AddChangeModule;